package org.jeecg.modules.demo.util;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;

import java.io.IOException;
import java.io.StringWriter;
 @Slf4j
public class DocumentUtil {
 

	
	/**
	 * Document 转换为 String 并且进行了格式化缩进
	 * 
	 * @param doc XML的Document对象
	 * @return String
	 */
	public static String doc2FormatString(Document doc) {	
		String docString = "";
		if(doc != null){
			StringWriter stringWriter = new StringWriter();
			try{
				OutputFormat format = new OutputFormat(doc,"UTF-8",true);
				//format.setIndenting(true);//设置是否缩进，默认为true
				//format.setIndent(4);//设置缩进字符数
				//format.setPreserveSpace(false);//设置是否保持原来的格式,默认为 false
				//format.setLineWidth(500);//设置行宽度
				XMLSerializer serializer = new XMLSerializer(stringWriter,format);
				serializer.asDOMSerializer();
				serializer.serialize(doc);
				docString = stringWriter.toString();
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(stringWriter != null){
		        	try {
						stringWriter.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
	        	}
			}
		}
//		log.error("XML内容："+docString);
		return docString;
	}



	
}